<?php

class CateController extends Controller{

    private $M_users;
    private $M_cates;
    private $M_roles;
    private $M_cate_has_roles;
    private $M_cate_has_users;

    private $parent_array;
    private $tree_array;

    /**
     * 构造方法
     * 初始化
     */
    public function __construct(){
        $this->M_users = Model::getInstance('users');
        $this->M_cates = Model::getInstance('cates');
        $this->M_roles = Model::getInstance('roles');
        $this->M_cate_has_roles = Model::getInstance('cate has roles');
        $this->M_cate_has_users = Model::getInstance('cate has users');

        $this->parent_array = array();//记录每一个父节点的地址引用
        $this->tree_array = array();//整颗树的数组
    }

    //模块首页
    public function index(){
        global $controller;

        $curr_page = (int)$this->input()->post('pageNum',1);
        $per_page  = (int)$this->input()->post('numPerPage',30);
        $cate_name = $this->input()->post('cate_name');
        $action_url = $this->input()->post('action_url');
        $filter = array();

        if($cate_name){
            $filter['cate_name'] = $cate_name;
        }

        if($action_url){
            $filter['action_url'] = $action_url;
        }

        $list = $this->M_cates->getCateList($curr_page,$per_page,$filter);

        $data = array(
            'controller'=>$controller,
            'list'=>$list,
        );
        Template::show('cate/index.php',$data);

    }
    public function add(){
        global $controller;

        $data = array(
            'controller'=> $controller
        );
        Template::show('cate/add.php',$data);
    }

    public function del(){

        $cate_id = $this->input()->get('cate_id');

        $cate_info = $this->M_cates->get($cate_id);

        if($cate_info['right_value'] - $cate_info['left_value'] > 1){

            $data = array(
                "statusCode"=>"300",
                "message"=>"该分类下有子分类，不能删除！",
            );
            echo Response::JSON(300,$data);
            return false;
        }

        $ret = $this->M_cates->delAllCate($cate_id);

        if($ret){
            $this->M_cate_has_roles->delByCateId($cate_id);
            $this->M_cate_has_users->delByCateId($cate_id);

            $child_node = $this->M_cates->getCateByLR($cate_info['left_value'],$cate_info['right_value']);

            foreach($child_node as $v){
                $this->M_cate_has_roles->delByCateId($v['cate_id']);
                $this->M_cate_has_users->delByCateId($v['cate_id']);
            }

            $data = array(
                "statusCode"=>"200",
                "message"=>"删除成功",
                "navTabId"=>"cate",
                "callbackType"=>"closeCurrent"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"删除失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    public function edit(){
        global $controller;

        $cate_id = (int)$this->input()->get('cate_id');

        $cate_info = $this->M_cates->get($cate_id);

        if($cate_info['parent_cate_id']){

            $parent_cate_info = $this->M_cates->get($cate_info['parent_cate_id']);

        }else{

            $parent_cate_info = array(
                'cate_id'=>0,
                'cate_name'=>'管理中心'
            );
        }

        $roles = $this->M_roles->getCateRoles($cate_id);

        $_role_ids = $_role_names = array();

        foreach($roles as $v){
            $_role_ids[] = $v['role_id'];
            $_role_names[] = $v['role_name'];
        }

        $data = array(
            'controller'=>$controller,
            'cate_info'=>$cate_info,
            'parent_cate_info'=>$parent_cate_info,
            'role_ids'=>implode(',',$_role_ids),
            'role_names'=>implode(',',$_role_names),
        );

        Template::show('cate/edit.php',$data);
    }

    public function getTree($user_id, $cate_id = null, $filter_show = false, $filter_child = false){
        $cate_arr = $this->M_cates->getTree($cate_id,$filter_show,$filter_child);

        foreach($cate_arr as $v){

            $node_num = ($v['right_value']-$v['left_value'] - 1)/2;

            if($v['parent_cate_id']){//如果没有parent_cate_id则是顶层

                $this->parent_array[$v['parent_cate_id']]['cate_child'][$v['cate_id']] = $v;

                if($node_num > 0){

                    $this->parent_array[$v['cate_id']] = &$this->parent_array[$v['parent_cate_id']]['cate_child'][$v['cate_id']];
                }

            }else{
                $this->tree_array[$v['cate_id']] = $v;

                if($node_num > 0){

                    $this->parent_array[$v['cate_id']] = &$this->tree_array[$v['cate_id']];
                }
            }
        }

        $user_cate_ids = $this->getCateIdsByUserId($user_id);

        $html_str = '';
        //组合返回用户菜单
        foreach((array)$this->tree_array as $value){
            if(in_array($value['cate_id'],$user_cate_ids) && $value['is_show']){
                $html_str .= '<div class="accordionHeader"><h2><span>Folder</span>'.$value['cate_name'].'</h2></div>';
                $html_str .= '<div class="accordionContent"><ul class="tree treeFolder">';

                if($value['cate_child']){
                    $html_str .= substr(substr($this->htmlTree($value['cate_child'],$user_cate_ids),4),0,-5);
                }

                $html_str .= '</ul></div>';
            }
        }

        return $html_str;
    }

    public function htmlTree($data,$user_cate_ids)
    {
        $html = '';
        foreach($data as $k => $v)
        {
            if(in_array($v['cate_id'],$user_cate_ids) && $v['is_show']){
                if(isset($v['cate_child']))
                {   //父亲找到儿子
                    $html .= '<li><a>'.$v['cate_name'].'</a>';
                    $html .= $this->htmlTree($v['cate_child'],$user_cate_ids);
                    $html .= '</li>';
                }else{
                    if(preg_match("/[a-zA-Z]$/",$v['action_url'])){//站内后台连接
                        $html .= '<li><a href="'.SITE_URL . 'index.php?a=' . $v['action_url'] . '" target="navTab" rel="' . $v['action_url'] . '">'.$v['cate_name'].'</a></li>';
                    }else{//站外系统页面嵌入
                        $parse_url_info = parse_url($v['action_url']);
                        $path_info = pathinfo($v['action_url']);
                        $html .= '<li><a href="'. $v['action_url'] .'" target="navTab" rel="'.$parse_url_info['host'].$path_info['filename'].'">'.$v['cate_name'].'</a></li>';
                    }
                }
            }
        }

        return '<ul>'.$html.'</ul>';
    }

    //获取用户所有的权限分类ID
    public function getCateIdsByUserId($user_id){

        static $caches = array();

        if($caches[$user_id]){

            return $caches[$user_id];

        }else{

            $rcate_ids = $this->M_cate_has_roles->getCateIdsByUserId($user_id);

            $ucate_ids =  $this->M_cate_has_users->getCateIdsByUserId($user_id);

            $cate_ids = array_unique(array_merge($rcate_ids,$ucate_ids));

            $caches[$user_id] = $cate_ids;
            return $cate_ids;
        }
    }

    //添加菜单选项
    public function ajaxAdd(){

        $cate_name = $this->input()->post('cate_name');

        if(!$cate_name){
            $data = array(
                "statusCode"=>"300",
                "message"=>"必须填写分类名",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $action_url = $this->input()->post('action_url');
        $parent_cate_id = $this->input()->post('parent_cate_id',0);
        $role_ids = $this->input()->post('role_ids',false);
        $is_show = $this->input()->post('is_show');

        $ret = $this->M_cates->addCate($cate_name,$action_url,$parent_cate_id,$is_show);
        if($ret){

            if($role_ids){
                $role_ids = explode(',',$role_ids);
                $role_ids = array_unique($role_ids);
                foreach($role_ids as $v){
                    if($v){
                        $this->M_cate_has_roles->addCateHasRoles($ret,$v);
                    }
                }
            }
            $data = array(
                "statusCode"=>"200",
                "message"=>"添加成功",
                "navTabId"=>"cate",
                "callbackType"=>"closeCurrent"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"添加失败",
            );
            echo Response::JSON(300,$data);
        }
        exit;
    }

    //编辑菜单选项
    public function ajaxEdit(){

        $cate_name = $this->input()->post('cate_name');

        if(!$cate_name){
            $data = array(
                "statusCode"=>"300",
                "message"=>"必须填写分类名",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $action = $this->input()->post('action_url');
        $parent_cate_id = $this->input()->post('parent_cate_id',0);
        $role_ids = $this->input()->post('role_ids',false);
        $is_show = $this->input()->post('is_show');
        $cate_id = $this->input()->post('cate_id');

        $ret = $this->M_cates->updateCate($cate_id,$cate_name,$action,$parent_cate_id,$is_show);

        if($ret){

            if($role_ids){
                $role_ids = explode(',',$role_ids);
                $role_ids = array_unique($role_ids);
                $this->M_cate_has_roles->delByCateId($cate_id);
                foreach($role_ids as $v){
                    if($v){
                        $this->M_cate_has_roles->addCateHasRoles($cate_id,$v);
                    }
                }
            }
            $data = array(
                "statusCode"=>"200",
                "message"=>"更新成功",
                "navTabId"=>"cate",
                "callbackType"=>"closeCurrent"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"更新失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    public function ajaxCateTree(){
        $menu_arr = $this->M_cates->getTree();
        $data = array(
            'menu_arr'=>$menu_arr,
        );
        Template::show('cate/cate_tree.php',$data);
    }
}